package com.sinoglobal.ningxia.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Map;

import android.content.Context;
import android.os.Environment;

import com.alibaba.fastjson.JSON;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.ConnectionUtil;

/**
 * @author sbk
 * @createdate 2014-3-17 下午8:10:57
 * @Description: 本地缓存
 */
public class LocalCache {

	public static final String CACHE_DIR = Environment.MEDIA_MOUNTED
			.equals(Environment.getExternalStorageState()) ? getExternalCacheDir(
			FlyApplication.context).getPath()
			: FlyApplication.context.getCacheDir().getPath();

	/**
	 * 获取程序外部的缓存目录
	 * 
	 * @param context
	 * @return
	 */
	public static File getExternalCacheDir(Context context) {
		final String cacheDir = "/Android/data/" + context.getPackageName()
				+ "/cache/";
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + cacheDir);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}

	/**
	 * 获取缓存文件名 POST
	 */
	public static String getFileName(String url, Map<String, Object> params) {
		StringBuffer buffer = new StringBuffer(url);
		if (params != null) {
			for (String key : params.keySet()) {
				buffer.append(key);
				buffer.append(params.get(key) == null ? null : params.get(key)
						.toString());
			}
		}
		return md5(buffer.toString());
	}

	/**
	 * 获取缓存文件名 GET
	 */
	public static String getFileName(String url) {
		return md5(url);
	}

	/**
	 * 返回md5后的值
	 * 
	 * @param url
	 * @return
	 */
	public static String md5(String name) {
		try {
			MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
			md5.update(name.getBytes("UTF-8"));
			byte messageDigest[] = md5.digest();

			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String t = Integer.toHexString(0xFF & messageDigest[i]);
				if (t.length() == 1) {
					hexString.append("0" + t);
				} else {
					hexString.append(t);
				}
			}
			return hexString.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @author sbk
	 * @createdate 2014-3-17 下午8:10:05
	 * @Description: 写入缓存
	 * @param fileName
	 * @param content
	 * 
	 */
	public static void writeFileCache(String fileName, String content) {
		ItktLog.i("write cache fileName==" + fileName);
		File temp = new File(CACHE_DIR, fileName);
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(new FileOutputStream(temp));
			dos.writeUTF(content);
			ItktLog.i("write cache sucess!");
		} catch (Exception e) {
			ItktLog.i("write cache failed!");
			e.printStackTrace();
		} finally {
			try {
				dos.close();
			} catch (IOException e) {
				//Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @author sbk
	 * @createdate 2014-3-17 下午8:09:45
	 * @Description: 加载缓存，缓存不存在时返回-1
	 * @param fileName
	 * @return
	 * 
	 */
	public static String loadFileCache(String fileName) {
		ItktLog.i("read cache fileName==" + fileName);
		String content = "";
		File temp = new File(CACHE_DIR, fileName);
		if (temp.exists()) {
			ItktLog.i("read cache sucess!");
			try {
				content = new DataInputStream(new FileInputStream(temp))
						.readUTF();
			} catch (Exception e) {
				//Auto-generated catch block
				ItktLog.i("read cache failed!");
				e.printStackTrace();
			}
			return content;
		} else {
			ItktLog.i("no cache");
			return content;
		}
	}

	/**
	 * @author sbk
	 * @createdate 2014-5-12 上午9:37:16
	 * @Description: 获取缓存数据
	 * @param sendParams
	 * @param vo
	 * @return
	 */
	public static <T> T getCache(String sendParams, Class<T> vo) {
		String result = LocalCache.loadFileCache(LocalCache
				.getFileName(ConnectionUtil.URL + sendParams));
		ItktLog.i("取出缓存：====" + result);
		if ("".equals(result)) {
			return null;
		}
		try {
			T v = JSON.parseObject(result, vo);
			return v;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
}
